/*
 * @Author: Baishui
 * @Date: 2021-10-08 15:37:33
 * @LastEditors: Baishui
 * @LastEditTime: 2021-10-08 16:34:36
 * @Description: file content
 */
import { RouteRecordRaw } from 'vue-router'
import moduleRoutes from './modules'
import { cloneDeep } from 'lodash-es'

// 过滤路由 - splice，从后遍历
// export function routeHandler(menu: any[]) {
//   const cloneRoutes = cloneDeep(moduleRoutes)
//   const flatMenu = flatMenuHandler(menu)

//   const hasRoute = (path: string) => {
//     return flatMenu.includes(path) || (path === '/' && flatMenu.includes('/home'))
//   }

//   const _routeHandler = (routes: RouteRecordRaw[]) => {
//     for (let i = routes.length - 1; i >= 0; i--) {
//       const route = routes[i]
//       if (!hasRoute(route.path)) {
//         routes.splice(i, 1)
//       } else {
//         if (route.children && route.children.length) {
//           _routeHandler(route.children)
//         }
//       }
//     }
//   }
//   _routeHandler(cloneRoutes)
//   return cloneRoutes
// }

// 过滤路由 - filter
export function routeHandler(menu: any[]) {
  const cloneRoutes = cloneDeep(moduleRoutes)
  const flatMenu = flatMenuHandler(menu)

  const hasRoute = (path: string) => {
    return flatMenu.includes(path) || (path === '/' && flatMenu.includes('/home'))
  }

  const _routeHandler = (routes: RouteRecordRaw[]) => {
    return routes.filter((route) => {
      if (hasRoute(route.path)) {
        if (route.children && route.children.length) {
          _routeHandler(route.children)
        }
        return true
      }
      return false
    })
  }
  return _routeHandler(cloneRoutes)
}

// depth
function flatMenuHandler(menu: any) {
  if (!menu.length) return []
  let flatMenu: any = []
  menu.forEach((item: any) => {
    if (item.path) {
      flatMenu.push(item.path)
    }
    if (item.children && item.children.length) {
      flatMenu = flatMenu.concat(flatMenuHandler(item.children))
    }
  })
  return flatMenu
}

// breadth ['/home', '/charts', '/comp', '/charts/d3', '/charts/echart', '/charts/zender', '/comp/basic', '/comp/tables']
// function flatMenuHandler(menu: any[]) {
//   if (!menu.length) return []

//   const flatMenu = []
//   let tempArr = [...menu]
//   let index = 0,
//     current: any

//   while ((current = tempArr[index++])) {
//     if (current.path) {
//       flatMenu.push(current.path)
//     }
//     if (current.children && current.children.length) {
//       tempArr = tempArr.concat(current.children)
//     }
//   }

//   return flatMenu
// }
